<template>
  <div class="studentProduct">
    <el-container>
      <!-- 名字搜索 -->
      <el-row type="flex">
        <el-col :span="4">
          <div class="grid-content">搜索:</div>
        </el-col>
        <el-col :span="20">
          <el-select
            v-model="namevalue"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入想要搜索的姓名"
            :remote-method="remoteMethod"
            :loading="loading">
            <el-option
              v-for="item in nameoptions"
              :key="item.name"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
          <el-button type="primary" @click="searchbtn" circle icon="el-icon-search" style="margin-left:10px;"></el-button>
          <el-button type="primary" @click="add" v-show="isadd">添加项目</el-button>
        </el-col>
      </el-row>
      <!-- 班级搜索 -->
      <el-row>
        <el-col :span="4">
          <div class="grid-content">选择班级:</div>
        </el-col>
        <el-col :span="20">
          <template>
            <el-select v-model="classvalue" filterable @change="classchange(classvalue)" @visible-change="classlist">
              <el-option label="全部"
                  value="all"></el-option>
              <el-option
                v-for="item in classoptions"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </template>
        </el-col>
      </el-row>
       <!-- 导出excel -->
      <div class="exportExcel">
        <el-button icon="iconfont icon-activity_type_ExcelExtraction"
            @click="exportExcel">导出excel数据</el-button>
      </div>
      <!-- 表格 -->
      <el-table  v-loading="loading" :data="tableData" style="width: 100%" height="100%" border>
        <el-table-column prop="headimgurl" label="头像" width="200" align="center">
          <template slot-scope="scope">
            <el-avatar shape="square"
                       :size="50"
                       fit="contain"
                       :src="scope.row.headimgurl">
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名">
        </el-table-column>
        <el-table-column prop="class" label="班级">
        </el-table-column>
        <el-table-column prop="productUrl" label="项目地址">
        </el-table-column>
        <el-table-column prop="" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="success" @click="handleShow"
              >查看</el-button
            >
            <el-button
              v-show="isedit"
              size="mini"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              v-show="isdel"
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination 
          background
          hide-on-single-page
          layout="prev, pager, next"
          @current-change="changePage"
          :page-size="dataCount"
          :total="total">
        </el-pagination>
      </div>
      <!-- 添加项目弹窗 -->
      <el-dialog
        title="添加项目"
        :visible.sync="addDialog"
        width="40%"
      >
        <el-form ref="add" :model="collectadd" label-width="80px">
          <el-form-item label="头像">
            <el-upload
              ref="uploadAvatar"
              class="avatar-uploader"
              action="http://www.chst.vip/students/uploadStuAvatar"
              list-type="picture-card"
              :on-success="handleAvatarSuccess"
              :on-remove="handleAvatarRemove"
              :limit="1"
              :multiple="false"
              name="headimgurl">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="collectadd.name"></el-input>
          </el-form-item>
          <el-form-item label="班级">
            <el-input v-model="collectadd.class"></el-input>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input v-model="collectadd.age"></el-input>
          </el-form-item>
          <el-form-item label="学历">
            <el-input v-model="collectadd.degree"></el-input>
          </el-form-item>
          <el-form-item label="项目地址">
            <el-input v-model="collectadd.productUrl"></el-input>
          </el-form-item>
          <el-form-item label="评价">
            <el-input v-model="collectadd.description"></el-input>
          </el-form-item>
          <el-form-item label="城市">
            <el-input v-model="collectadd.city"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addproduct">添加</el-button>
            <el-button @click="addDialog = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 编辑项目弹窗 -->
      <el-dialog
        title="编辑"
        :visible.sync="editDialog"
        width="40%"
      >
        <el-form ref="add" :model="collectedit" label-width="80px">
          <el-form-item label="头像">
            <el-input v-model="collectedit.headimgurl"></el-input>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="collectedit.name"></el-input>
          </el-form-item>
          <el-form-item label="班级">
            <el-input v-model="collectedit.class"></el-input>
          </el-form-item>
          <el-form-item label="项目地址">
            <el-input v-model="collectedit.productUrl"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="editstu">编辑</el-button>
            <el-button @click="editDialog = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-container>
  </div>
</template>
<script>
//引入actions的辅助函数
// import { mapActions } from "vuex";
// 引入state的辅助函数
// import { mapState } from "vuex";
//引入execl导出插件
import qee from "qf-export-excel"
import {mapGetters} from "vuex"
import {getStuList,addStu,updateStu,delStu,getClassList,searchStu} from "../../../api/index"
export default { 
  data() {
    return {
      tableData:[],//渲染表格的数据
      dataPage: '', // 页码
      dataCount: 5, // 每页展示的数量
      total: 0, // 总共的数据条数
      loading:false,//动画
      imageUrl:"",
      namevalue:"",
      classvalue:"",
      nameoptions:[],
      classoptions:[],
      searchinput:"",//存储自己搜索的内容
      addDialog:false,//弹窗是否显示
      editDialog:false,//弹窗是否显示
      collectadd: {   //添加项目弹出框存储数据
        headimgurl: "",
        name: "",
        productUrl: "",
        class: "",
        age: "",
        city: "",
        degree: "",
        description: "",
      },
      collectedit:{ //编辑弹出框存储数据
        sId:"",
        avatar: "",
        name: "",
        productUrl: "",
        class: ""
      }
    };
  },
  methods: {
    handleAvatarSuccess(response, file, fileList){
      //上传成功时，给dialog所属的collectadd里的headimgurl赋值服务器返回的地址
      this.collectadd.headimgurl=response.headimgurl
    },
    handleAvatarRemove(file, fileList){
      //失败时，清空
      this.collectadd.headimgurl=""
    },
    //导出EXCEL
    exportExcel(){
      const titleList = [
        {
          title: '头像',
          key: 'headimgurl'
        },
        {
          title: '姓名',
          key: 'name'
        },
        {
          title: '班级',
          key: 'class'
        },
        {
          title: '项目',
          key: 'productUrl'
        }
      ]
      const dataSource = this.tableData
      qee(titleList, dataSource, '学员数据')
    },
    // 搜索请求
    remoteMethod(query){
      this.searchinput=query
      searchStu(query)
      .then(res=>{
        this.loading=true
        if(res.data.state){
          this.nameoptions=res.data.data
          setTimeout(()=>{
            this.loading=false
          },300)
        }else{
          this.loading=false
        }  
      })
      .catch(err=>{
          console.log(err)
          this.$message({ message: "搜索失败", type: "warning" })
          this.loading=false
      })
    },
    // 搜索框旁的按钮，根据搜索框内的快捷标签进行全局搜索
    searchbtn(){
      this.classvalue=""
      if(this.namevalue.length){
        getStuList()
        .then(res=>{
          this.loading=true
          if(res.data.state){
            let arr=res.data.data
            let newarr=[]
            this.namevalue.forEach((index)=>{
              return arr.filter((item)=>{
                return item.name == index?newarr.push(item):null
              })
            })
            this.tableData=newarr
            setTimeout(()=>{
              this.loading=false
            },300)
          }else{
            this.$message({ message: "搜索失败", type: "warning" })
            this.loading=false
          }
        })
        .catch(err=>{
          console.log(err)
          this.$message({ message: "搜索失败", type: "warning" })
          this.loading=false
        })
      }else{
        if(this.searchinput){
          searchStu(this.searchinput)
          .then(res=>{
            this.loading=true
            if(res.data.state){
              this.tableData=res.data.data
              this.loading=false
              this.searchinput=""
            }
          })
        }else{
          this.update()
        }
      }
    },
    // 更新视图(重新请求一次数据)
    update(params){
      if(params){
        getStuList(params)
        .then(res=>{
          this.loading=true
          if(res.data.state){
            this.tableData=res.data.data
            setTimeout(()=>{
              this.loading=false
            },300)
          }else{
            this.$message({ message: "获取数据失败", type: "warning" })
            this.loading=false
          }
        })
        .catch(err=>{
          console.log(err)
          this.loading=false
          this.$message({ message: "获取数据失败", type: "warning" })
        })
      }else{
        getStuList()
        .then(res=>{
          this.loading=true
          if(res.data.state){
            this.tableData=res.data.data
            setTimeout(()=>{
              this.loading=false
            },300)
          }else{
            this.$message({ message: "获取数据失败", type: "warning" })
            this.loading=false
          }
        })
        .catch(err=>{
          console.log(err)
          this.loading=false
          this.$message({ message: "获取数据失败", type: "warning" })
        })
      }
    },
    //班级选择框展开/收起触发的事件,用于获取所有班级列表
    classlist(){
      getClassList()
      .then(res=>{
        if(res.data.state){
          this.classoptions=res.data.data
        }
      })
      .catch(err=>{
        console.log(err)
      })
    },
    // 点击班级选择框后，更新结果渲染表格
    classchange(classvalue){
      this.namevalue=""
      if(classvalue == "all"){
        this.update()
      }else{
        let params={class:classvalue}
        this.update(params)
      }
    },
    // 弹出添加输入框
    add(){
      this.addDialog=true
    },
    // 点击添加输入框里的添加按钮
    addproduct() {
      let addinfo = {
        name: this.collectadd.name,
        class: this.collectadd.class,
        age: this.collectadd.age,
        city: this.collectadd.city,
        degree: this.collectadd.degree,
        productUrl: this.collectadd.productUrl,
        description: this.collectadd.description,
        headimgurl: this.collectadd.headimgurl
      };
      addStu(addinfo)
      .then(res=>{
        this.loading=true
        if(res.data.state){
          console.log(res.data.state)
          this.update()
          this.classlist()
          this.$message({ message: "添加成功", type: "success" })
          //dialog添加成功时，清空collectadd里所有的数据
          Object.keys(this.collectadd).forEach((item)=>this.collectadd[item]="")
          //清空ElementUi中上传组件的文件列表，调用官方方法
          this.$refs["uploadAvatar"].clearFiles()
        }else{
          this.$message({ message: "添加失败", type: "warning" })
          this.loading=false
        }
      })
      .catch(err=>{
          console.log(err)
          this.$message({ message: "添加失败", type: "warning" })
          this.loading=false
      })
      this.addDialog = false;
    },
    handleShow(){

    },
    // 弹出编辑输入框
    handleEdit(index, row){
      this.editDialog=true
      this.collectedit = Object.assign({}, row)
    },
    // 点击编辑输入框里的编辑按钮
    editstu(){
      let token = localStorage.getItem("stu-login-token");
      let updateInfo = {
        token: token,
        sId:this.collectedit.sId,
        headimgurl: this.collectedit.headimgurl,
        name: this.collectedit.name,
        class: this.collectedit.class,
        productUrl: this.collectedit.productUrl,
      }
      updateStu(updateInfo)
      .then(res=>{
        this.loading=true
        if(res.data.state){
          this.tableData = this.tableData.map(item => {
            return item.sId ==  updateInfo.sId ?  updateInfo : item;
          })
          if(this.namevalue){
            this.searchbtn()
          }else{
            this.classvalue?this.update({class:this.classvalue}):this.update()
          }
          this.$message({ message: "修改成功", type: "success" })
        }else{
          this.$message({ message: "修改失败", type: "warning" })
          this.loading=false
        }
      })
      .catch(err=>{
          this.$message({ message: "修改失败", type: "warning" })
          this.loading=false
      })
      this.editDialog = false;
    },
    // 点击删除
    handleDelete(index, row){
      delStu(row.sId)
      .then(res=>{
        this.loading=true
        if(res.data.state){
          let result = this.tableData.find(item => {
            return item.sId == row.sId;
          });
          let index = this.tableData.indexOf(result);
            this.tableData.splice(index, 1);
            if(this.namevalue){
              this.searchbtn()
            }else{
              this.classvalue?this.update({class:this.classvalue}):this.update()
            }
            this.$message({ message: "删除成功", type: "success" })
        }else{
            this.$message({ message: "删除成功", type: "warning" })
            this.loading=false
        }
      })
      .catch(err=>{
          this.$message({ message: "删除失败", type: "warning" })
          this.loading=false
      })
    },
    //分页器
    changePage(currentpage){
      console.log(currentpage)
    },
  },
  computed: {
    ...mapGetters(["isadd"]),
    ...mapGetters(["isedit"]),
    ...mapGetters(["isdel"])
  },
  mounted() {
    this.update()
  }
};
</script>
<style>
.studentProduct {
  height: 550px;
}
.studentProduct .el-row {
  width: 60%;
  height: 60px;
  margin-top: 25px;
}
.studentProduct .el-row .el-col-4 {
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-size: 20px;
  font-weight: 800;
}
.studentProduct .el-container {
  flex-direction: column;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 154px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .pagination {
    margin-top: 20px;
  }
  .exportExcel{
    position:absolute;
    top: 228px;
    right: 22px;
  }
  .exportExcel>button{
    padding: 5px 10px;
  }
</style>
